package dl.jf.web.filter;

import java.util.Map;
import org.apache.log4j.Logger;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.sun.xml.internal.bind.v2.runtime.reflect.opt.Const;

import dl.jf.common.constants.Constants;
import dl.jf.common.model.LabelValue;
import dl.jf.common.model.MUser;
import dl.jf.service.iservice.ICommonService;
import dl.jf.service.iservice.ILoginService;


public class AdminAuthorizationInterceptor extends AbstractInterceptor {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1168043600535031022L;

	/**
     * 
     */
    private static Logger log = Logger.getLogger(AdminAuthorizationInterceptor.class);
    
    private ILoginService loginService;

	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}
    
    private ICommonService commonService;

	public void setCommonService(ICommonService commonService) {
		this.commonService = commonService;
	}
    
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
    	
        Map session = invocation.getInvocationContext().getSession();
        String success = (String) session.get(Constants.LOGIN_SUCCESS);
        log.debug("success=" + success);
        if (success == null || !"true".equals(success)) {
            log.debug("please login");
            session.clear();
            return Constants.ACTION_RESULT_TO_LOGIN;
        }
        String userId = (String) session.get("userId");
        if (userId == null || "".equals(userId)) {
            session.clear();
            return Constants.ACTION_RESULT_TO_LOGIN;
        }
        MUser accessUser = loginService.getUserInfoByUserId(userId);
        if (accessUser == null || accessUser.getRoleId() > Constants.ADMIN_ROLE_ID) {
            log.warn("User " + userId + " dosen't exist.");
            return Constants.ACTION_RESULT_NO_ADMIN_PERMISSION;
        } else {
        	log.debug("success admin access");
            return invocation.invoke();
        }
    }
}